package sessionadmin

import (
	"net"
	"src/iinf"
	"src/log"
	"time"
)

// ClientAdmin ClientAdmin
type ClientAdmin struct {
	Admin
	cursession iinf.Session
	timer      *time.Timer
}

//AddSession AddSession
func (sa *ClientAdmin) AddSession(ses iinf.Session) {
	sa.lock()
	defer sa.unLock()

	if sa.cursession != nil {
		panic("cursession is not nil so i don`t kown how to do now!!!!!!!!!!!!")
	}
	sa.cursession = ses
	sa.smap[ses.GetID()] = ses
	sa.timer = time.AfterFunc(5*time.Second, func() {
		if sa.cursession != nil {
			log.Println("timeout now close this session")
			sa.cursession.Close()
			sa.cursession = nil
		}
	})
}

//DelSession DelSession
func (sa *ClientAdmin) DelSession(ses iinf.Session) {
	sa.lock()
	defer sa.unLock()

	delete(sa.smap, ses.GetID())
}

//AddDevConn AddDevConn
func (sa *ClientAdmin) AddDevConn(conn net.Conn) {
	if sa.cursession != nil {
		sa.timer.Stop()
		sa.cursession.Init(conn)
		sa.cursession = nil
	}
}

//IsBusy IsBusy
func (sa *ClientAdmin) IsBusy() bool {
	return sa.cursession != nil
}

//GetNewClientAdmin GetNewClientAdmin
func GetNewClientAdmin() *ClientAdmin {
	return &ClientAdmin{
		Admin: Admin{
			smap: make(map[int]iinf.Session),
		},
	}
}
